package com.evry.sandox.batch;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import org.springframework.batch.item.ItemWriter;

import com.evry.sandox.batch.domain.CollateralItem;
import com.evry.sandox.batch.exceptions.TimeOutWebServiceException;
import com.evry.sandox.batch.exceptions.ValidationWebServiceException;

public class CustomItemWriter implements ItemWriter<CollateralItem>{

	public void write(List<? extends CollateralItem> items) throws Exception {
		System.out.println("CustomItemWriter: before chunk.");
		for (CollateralItem collateralItem : items) {
			System.out.println("Sending ... " + collateralItem.getName());
			if(collateralItem.getId().equals(new BigDecimal(5))){	
				System.out.println("EXCEPTION: " + collateralItem.getName() + " is invalid");
				throw new ValidationWebServiceException("The collateral " + collateralItem.getName() + " is invalid and has been rejected.");
			}
			if(collateralItem.getId().equals(new BigDecimal(2))){
				if(Math.random()< 0.99){
					System.out.println("EXCEPTION: Time outed " + collateralItem.getName()  + " date: " + new Date());
					throw new TimeOutWebServiceException("Web service timed out trying to insert " + collateralItem.toString() + ".");
				}
			}
			System.out.println("Successfully sent " + collateralItem.getName());
		}
		System.out.println("CustomItemWriter: after chunk.");
		
	}
}
